<template>
  <form-item-wrapper :field="field">
    <el-table :data="field.rows" border :style="tableStyle" class="tableWidget">
      <el-table-column
        v-for="(col, colIdx) in field.cols"
        :prop="colIdx === 0 ? 'sn' : col.name ? col.name : ''"
        :label="colIdx === 0 ? 'sn' : col.name ? col.name : ''"
        :fixed="colIdx === 0"
        :width="colIdx === 0 ? 80 : col.width || 180"
        :key="colIdx"
      >
        <template #header>
          <template v-if="colIdx === 0">
            <div
              :style="{
                height: '44px',
                lineHeight: '44px',
                marginLeft: '15px',
              }"
            >
              No.
            </div>
          </template>
          <template v-if="colIdx !== 0">
            <template v-if="col.name">
              <div
                @click.stop="handelColClick(col, colIdx)"
                class="tableWidget__colItem"
              >
                {{ col.name }}
              </div>
            </template>
            <template v-else>
              <vue-draggable-next
                v-bind="{ group: 'dragGroup', ghostClass: 'ghost' }"
                :component-data="{ name: 'fade' }"
                class="table"
                handle=".drag-handler"
                tag="transition-group"
                @add="(evt) => onTableDragAdd(evt, colIdx)"
              >
                <div class="dragContent">
                  <el-icon><Rank /></el-icon>
                  拖拽试题至此
                </div>
              </vue-draggable-next>
            </template>
          </template>
        </template>
        <template #default="scope">
          <template v-if="colIdx === 0">
            <div class="tableWidget__rowName">{{ scope.row }}</div>
          </template>
          <template v-else>
            <template v-if="formStore.isDesigner">
              <component
                :is="getWidget(col.type)"
                :field="col"
                :colIdx="colIdx"
                :key="`${colIdx}_${scope.$index}`"
                @answer-change="handelAnswerChange"
              />
            </template>
            <template v-else>
              <component
                :is="getWidget(col.type)"
                :field="col2arr[scope.$index][colIdx]"
                :colIdx="colIdx"
                :key="`${colIdx}_${scope.$index}`"
                @answer-change="handelAnswerChange"
              />
            </template>
          </template>
        </template>
      </el-table-column>
    </el-table>
  </form-item-wrapper>
</template>
<script lang="ts" setup>
import { VueDraggableNext } from "vue-draggable-next";
import FormItemWrapper from "../field-wdiget/form-item-wrapper.vue";
import { computed, onMounted, PropType, ref } from "vue";
import QuestionType from "@bis/types/question";
import { useFormStore } from "@bis/stores/form";
import { deepClone } from "@bis/utils/objectFun";
import FieldComps from "../field-wdiget";
import { editQue } from "../../../utils";

const formStore = useFormStore();

const props = defineProps({
  field: Object as PropType<QuestionType>,
});

const col2arr = ref([]);

const tableStyle = computed(() => {
  let width: number | string = 0;
  props.field.cols.forEach((col, colIdx) => {
    if (colIdx == 0) {
      width += 50;
    } else {
      width += col.width || 180;
    }
  });
  width = width + 30 + "px";
  return {
    width: width,
    maxWidth: "100%",
  };
});

const getCol2Arr = () => {
  let _ = [];
  const { cols, rows, answer } = props.field;
  rows.forEach((row, rowIdx) => {
    const arr = cols.map((col) => {
      col.id = rowIdx;
      return deepClone(col);
    });
    _.push(arr);
  });
  if (formStore.isDesigner || !answer) {
    props.field.answer = Array.from({ length: rows.length }, () =>
      Array.from({ length: cols.length }, () => "")
    );
  } else {
    let arr = [];
    if (typeof answer === "string") {
      const _arr = answer.split("__");
      _arr.forEach((item) => {
        arr.push(item.split("$$"));
      });
    } else {
      arr = answer;
    }
    props.field.answer = arr;
    _.map((item, idx) => {
      item.map((col, colIdx) => {
        col.answer = arr[idx][colIdx];
      });
    });
  }
  col2arr.value = _;
};

const getWidget = (type) => {
  return FieldComps[`${type}-widget`];
};

const handelColClick = (field, colIdx) => {
  field.colIdx = colIdx;
  formStore.setSelectQuestion(field);
};

const onTableDragAdd = (evt: { [key: string]: any }, colIdx) => {
  props.field.cols[colIdx] = deepClone(evt.item._underlying_vm_);
  props.field.cols[colIdx].containerId = props.field.id;
  props.field.cols[colIdx].width = 150;
  if (formStore.isDesigner) {
    props.field.cols[colIdx].disabled = true;
  }
  props.field.cols.push({});
  formStore.setSelectQuestion(props.field);
  // 调用保存
  editQue(props.field, formStore);
};

const handelAnswerChange = (val, colIdx) => {
  const { answer, id } = val;
  props.field.answer[id][colIdx] = answer;
};

const init = () => {
  getCol2Arr();
};

onMounted(() => {
  init();
});
</script>
<style lang="scss" scoped>
@import "./table-widget.scss";
</style>
